<!-- 服务入驻申请 -->
<template>
	<view style="width: 100%;">
		<view style="width: 100%;height: 100%;" v-if="status === 0">
			<uni-nav-bar title="服务入驻申请" @clickLeft="back" left-icon="left" backgroundColor="#fff" color="#000"
				statusBar="true">
			</uni-nav-bar>
			<view v-if="true">
				<scroll-view class="scrollheight" scroll-y="true" :style="{height:setcollapseheight() - 90 + 'px'}">
				<u--form labelPosition="left" :model="model" :rules="rules" ref="form">
					<!-- 1.服务类型 -->
					<u-form-item label="服务类型" prop="formData.typeName" borderBottom
						@click="hideKeyboard()">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/type.png" mode="heightFix"></image>
						</view>
						<picker mode=selector @cancel="servicetypeClose" @change="selectType" range-key="name"
							:value="model.formData.typeName" :range="typeList">
							<u--input v-model="model.formData.typeName" style="pointer-events: none" disabled
								disabledColor="#ffffff" placeholder="请选择服务类型" border="none"></u--input>
							<u-icon name="arrow-down"></u-icon>
						</picker>
					</u-form-item>
					<!-- 2.入驻运营方 -->
					<u-form-item label="入驻运营方" prop="formData.operatorName" borderBottom>
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/huodongyunying.png" mode="heightFix"></image>
						</view>
						<picker mode=selector @cancel="selectOperatorClose" @change="selectOperator" range-key="name"
							:value="model.formData.operatorName" :range="operatorList">
							<u--input v-model="model.formData.operatorName" style="pointer-events: none" disabled
								disabledColor="#ffffff" placeholder="请选择入驻运营方" border="none"></u--input>
							<u-icon name="arrow-down"></u-icon>
						</picker>
					</u-form-item>
					<!-- 3.服务方名称 -->
					<u-form-item label="服务方名称" prop="formData.name">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/fuwufang.png" mode="heightFix"></image>
						</view>
						<u--input v-model="model.formData.name" placeholder='请输入名称' border="none"></u--input>
					</u-form-item>
					<!-- 4.1.所在区域-省市区 -->
					<u-form-item :label="label1" prop="formData.AllName" @click="goMap">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/address.png" mode="heightFix"></image>
						</view>
						<!-- <picker mode="multiSelector" :range="areaList" range-key="name" :value="value"
							@columnchange="columnchange" @change="bindPickerChange">
							<u--input v-model="model.formData.AllName" style="pointer-events: none" disabled
								disabledColor="#ffffff" border="none" placeholder='请选择所在区域'></u--input>
						</picker> -->
						<template v-if="model.formData.AllName">
							<view>
								<u--input v-model="model.formData.AllName" style="pointer-events: none" disabled
									disabledColor="#ffffff" border="none" placeholder='请选择所在区域'></u--input>
							</view>
						</template>
						<template v-else>
							<view class="lnglat">
								选择地址<u-icon name="arrow-right" class="icon" color="#0752fd"></u-icon>
							</view>
						</template>
					</u-form-item>
					<!-- 4.服务地址 -->
					<u-form-item label="详细地址" prop="formData.address" class="fullAddress">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service-order/jutidizhi.png" mode="heightFix"></image>
						</view>
						<u--textarea class="textarea" v-model="model.formData.address" placeholder='请输入具体地址' border="none"
							style="display: flex;"></u--textarea>
					</u-form-item>
					<!-- 服务半径 -->
					<u-form-item label="服务半径" prop="formData.radius">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/fuwufang.png" mode="heightFix"></image>
						</view>
						<u--input v-model="model.formData.radius" type="number" placeholder='请输入服务半径' border="none"></u--input>
					</u-form-item>
					<!-- 5.机构法人 -->
					<u-form-item :label="label2" prop="formData.contactor">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/organization-person.png" mode="heightFix"></image>
						</view>
						<u--input v-model="model.formData.contactor" placeholder='请输入法人名称' border="none"></u--input>
					</u-form-item>
					<!-- 6.联系电话 -->
					<u-form-item label="联系电话" prop="formData.contactPhone">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/lianxidianhua.png" mode="heightFix"></image>
						</view>
						<u--input v-model="model.formData.contactPhone" placeholder='请输入联系方式' type="number"
							border="none"></u--input>
					</u-form-item>
					<!-- 7.营业执照  -->
					<u-form-item :label="label3" prop="formData.imgList" style="background-color: #E2E7F8;">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/yingyezhizhao.png" mode="heightFix"></image>
						</view>
						<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							deletable :maxCount="1">点击上传</u-upload>
					</u-form-item>
					<!-- 8.机构图片 -->
					<u-form-item label="机构图片" prop="formData.imgList1" style="background-color: #E2E7F8;">
						<view class="left-image">
							<image class="left-img" src="@/subPage1/static/service/tuwenxiangqing.png" mode="heightFix"></image>
						</view>
						<u-upload :fileList="fileList1" @afterRead="afterRead1" @delete="deletePic1" name="1" multiple
							deletable :maxCount="1">点击上传</u-upload>
					</u-form-item>
				</u--form>
				<!-- 1.服务类型description="如果选择保密会报错" -->
				<!-- <u-action-sheet :show="showServicetype" :actions="typeList" title="请选择服务类型"
					@close="showServicetype = false;servicetypeClose()" @select="selectType">
				</u-action-sheet> -->
				</scroll-view>
				<view class="record-add-view">
					<!-- 提交 -->
					<view class="submit">
						<button @click="application()" class="submit-btn">
							<text>提交申请入驻</text>
						</button>
					</view>
				</view>
			</view>
			<view class="blank" v-else>
				<image src="@/static/blank.png" mode="heightFix"></image>
				<view class="title">
					您近期已申请过入驻，您可以在消息功能中留意入驻申请结果。
				</view>
			</view>
		</view>
		<view v-else style="width: 100%;">
			<Maps @changeStatus="changeStatus" />
		</view>
	</view>
</template>

<script>
	import { addressList } from '@/subPage1/plugins/address.js'
	import API from '@/api/socialized-servce/farm-service/person-message/server-application/index.js'
	import agriculturalApi from '@/api/socialized-servce/agricultural-information/index.js'
	import {
		agrServiceUrl
	} from '@/config/baseUrl.js'
	import Maps from '@/subPage1/map1/map1.vue'
	export default {
		components: {
			Maps
		},
		data() {
			return {
				status: 0,
				label1: '机构地址',
				label2: '机构法人',
				label3: '营业执照',
				label4: '机构图片',
				model: {
					formData: {
						userId: uni.getStorageSync('userId'),
						typeName: '',
						type: '',
						operatorName: '',
						serviceProviderNo: '',
						name: '',
						AllName: '',
						serviceProvinceId: '',
						serviceCityId: '',
						serviceAreaId: '',
						address: '',
						contactor: '',
						contactPhone: '',
						imgList: [],
						imgList1: [],
						radius: '',
						latitude: '',
						longitude: ''
					}
				},
				rules: {
					'formData.typeName': {
						type: 'string',
						required: true,
						message: '请选择服务类型',
						trigger: ['blur', 'change']
					},
					'formData.operatorName': {
						type: 'string',
						required: true,
						message: '请选择入驻运营方',
						trigger: ['blur', 'change']
					},
					'formData.name': {
						type: 'string',
						required: true,
						message: '服务方名称不能为空',
						trigger: ['blur', 'change']
					},
					'formData.AllName': {
						type: 'string',
						required: true,
						message: '所在区域不能为空',
						trigger: ['blur', 'change']
					},
					'formData.address': {
						type: 'string',
						required: true,
						message: '地址不能为空',
						trigger: ['blur', 'change']
					},
					'formData.radius': {
						type: 'number',
						required: true,
						message: '服务半径不能为空',
						trigger: ['blur', 'change']
					},
					'formData.contactor': {
						type: 'string',
						required: true,
						message: '法人名称不能为空',
						trigger: ['blur', 'change']
					},
					'formData.contactPhone': [{
							type: 'string',
							required: true,
							message: '联系电话不能为空',
							trigger: ['blur', 'change']
						},
						{
							type: 'string',
							validator: (rule, value, callback) => {
								if (value.length <= 11) {
									if (value != '') {
										return this.$u.test.mobile(value)
									}
								} else {
									return false
								}
							},
							message: '手机号格式不对,请输入正确的手机号',
							trigger: ['blur', 'change']
						}
					],
					'formData.imgList': {
						type: 'array',
						required: true,
						message: '请上传营业执照',
						trigger: ['blur', 'change']
					},
					'formData.imgList1': {
						type: 'array',
						required: true,
						message: '请上传机构图片',
						trigger: ['blur', 'change']
					}
				},
				// 目前写死
				typeList: [{
						name: '个人',
						type: 1
					},
					{
						name: '机构',
						type: 2
					}
				],
				operatorList: [],
				// 图片
				fileList: [],
				fileList1: [],
				// 省市区
				areaList: [],
				value: [0, 0, 0],
				index: 0,
				AllAddress: addressList,
				selectVal: ['', '', ''],
				timer: null
			}
		},
		onLoad(e) {},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		created() {
			this.init()
			// this.initSelect()
			let userServerInfo = JSON.parse(uni.getStorageSync('userServerInfo'))
			this.model.formData.contactor = userServerInfo.userName
			this.model.formData.contactPhone = userServerInfo.phoneNumber
			console.log(uni.getStorageSync('formatted_address'));
		},
		mounted() {
			this.setcollapseheight()
		},
		beforeDestroy() {
			this.timer = null
		},
		methods: {
			async init() {
				let address = uni.getStorageSync('formatted_address')
				if(address) {
					this.model.formData.longitude = uni.getStorageSync('lng')
					this.model.formData.latitude = uni.getStorageSync('lat')
					var reg = /.+?(省|市|自治区|自治州|县|区)/g;
					let arr = address.match(reg).toString().split(",");
					this.model.formData.AllName = `${arr[0]}${arr[1]}${arr[2]}`
					this.model.formData.address = address
					addressList.forEach(item => {
						if (item.name === arr[0]) {
							this.model.formData.serviceProvinceId = item.provinceId
						}
						item.city.forEach(item1 => {
							if (item1.name === arr[1] && item.name === arr[0]) {
								this.model.formData.serviceCityId = item1.cityId
							}
							if (item1.name === '市辖区' && item.name === arr[0]) {
								this.model.formData.serviceCityId = item1.cityId
							}

							item1.area.forEach(item2 => {
								if (item2.name === arr[2] && item.name === arr[0]) {
									this.model.formData.serviceAreaId = item2.areaId
								}
							})
						})
					})
				}
				let params = {
					status: 0
				}
				let res = await agriculturalApi.queryOperator(params)
				if(res.code === 200) {
					this.operatorList = res.data
				}
			},
			goMap() {
				this.status = 1
			},
			changeStatus() {
				this.status = 0
				this.init()
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			// 1.选择服务类型
			servicetypeClose() {
				this.$refs.form.validateField('formData.typeName')
			},
			selectType(e) {
				// this.fileList = []
				// this.fileList1 = []
				// this.model.formData.imgList = []
				// this.model.formData.imgList1 = []
				// this.$refs.form.resetFields()
				if (e.detail.value === 0) {
					this.label1 = '机构地址'
					this.label2 = '机构法人'
					this.label3 = '营业执照'
				} else {
					this.label1 = '服务地址'
					this.label2 = '联系人'
					this.label3 = '身份证'
				}
				this.model.formData.typeName = this.typeList[e.detail.value].name
				this.model.formData.type = e.detail.value + 1
				this.$refs.form.validateField('formData.typeName')
			},
			// 2.选择运营方
			selectOperatorClose() {
				this.$refs.form.validateField('formData.operatorName')
			},
			selectOperator(e) {
				this.model.formData.operatorName = this.operatorList[e.detail.value].name
				this.model.formData.serviceProviderNo = this.operatorList[e.detail.value].serviceProviderNo
				this.$refs.form.validateField('formData.operatorName')
			},
			// 省市区
			bindPickerChange(e) {
				let obj = addressList[this.value[0]]
				this.model.formData.serviceProvinceId = obj.provinceId
				this.model.formData.serviceCityId = obj.city[this.value[1]].cityId
				this.model.formData.serviceAreaId = obj.city[this.value[1]].area[this.value[2]].areaId
				// console.log(this.model.formData.serviceProvinceId);
				// console.log(this.model.formData.serviceCityId);
				// console.log(this.model.formData.serviceAreaId);
				this.$refs.form.validateField('formData.AllName')
			},
			columnchange(d) {
				this.updateSelectIndex(d.detail.column, d.detail.value) // 更新选择索引
					.updateSourceDate() // 更新源数据
					.updateAddressDate() // 更新结果数据
			},
			initSelect() {
				this.updateSourceDate() // 更新源数据
				this.updateAddressDate() // 更新结果数据
			},
			updateSourceDate() {
				this.areaList = []
				this.areaList[0] = this.AllAddress.map(obj => {
					return {
						name: obj.name
					}
				})
				this.areaList[1] = this.AllAddress[this.value[0]].city.map(obj => {
					return {
						name: obj.name
					}
				})
				this.areaList[2] = this.AllAddress[this.value[0]].city[this.value[1]].area.map(obj => {
					return {
						name: obj.name
					}
				})
				return this
			},
			updateSelectIndex(column, value) {
				let arr = JSON.parse(JSON.stringify(this.value))
				arr[column] = value
				if (column === 0) {
					arr[1] = 0
					arr[2] = 0
				}
				if (column === 1) {
					arr[2] = 0
				}
				this.value = arr
				return this
			},
			updateAddressDate() {
				this.selectVal[0] = this.areaList[0][this.value[0]].name
				this.selectVal[1] = this.areaList[1][this.value[1]].name
				this.selectVal[2] = this.areaList[2][this.value[2]].name
			
				if (this.value[0] == 0 && this.value[1] == 0 && this.value[2] == 0) {
					this.model.formData.AllName = ''
				} else {
					this.model.formData.AllName = `${this.selectVal[0]} ${this.selectVal[1]} ${this.selectVal[2]}`
				}
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.model.formData.imgList.splice(event.index, 1)
				this.$refs.form.validateField('formData.imgList')
			},
			deletePic1(event) {
				this.fileList1.splice(event.index, 1)
				this.model.formData.imgList1.splice(event.index, 1)
				this.$refs.form.validateField('formData.imgList1')
			},
			// 驾驶证
			async afterRead(event) {
				this.type = 'image'
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: `${agrServiceUrl}${result.slice(1)}`
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: agrServiceUrl + `common/file/upDown/getUploadUrl?moduleType=XG_ORGANIZATION&upDownType=FTP`,
						filePath: url,
						name: 'file',
						header: {
							'token': uni.getStorageSync("satoken") || ''
						},
						formData: {},
						success: async (res) => {
							const dataObj = JSON.parse(res.data);
							const data = dataObj.data;
							console.log(data, '图片');
							resolve(data);
							if (this.type == 'image') {
								this.model.formData.imgList.push({
									imgId: data.slice(33),
									imgUrl: `${agrServiceUrl}${data.slice(1)}`
								})
								this.$refs.form.validateField('formData.imgList')
							} else if (this.type == 'image1') {
								this.model.formData.imgList1.push({
									imgId: data.slice(33),
									imgUrl: `${agrServiceUrl}${data.slice(1)}`
								})
								this.$refs.form.validateField('formData.imgList1')
							}
						},
						fail: () => {
							uni.showToast({
								title: '图片上传失败',
								icon: 'error'
							})
						}
					});
				})
			},
			// 行驶证
			async afterRead1(event) {
				this.type = 'image1'
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList1.length
				lists.map((item) => {
					this.fileList1.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList1[fileListLen]
					this.fileList1.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: `${agrServiceUrl}${result.slice(1)}`
					}))
					fileListLen++
				}
			},
			// 申请入驻
			application() {
				this.$refs.form.validate().then(async () => {
					console.log("提交表单信息:" ,this.model.formData);
					let params = {
						...this.model.formData
					}
					delete params.typeName
					delete params.operatorName
					delete params.imgList
					delete params.imgList1
					delete params.AllName
					// 机构图片
					if(this.model.formData.imgList1.length>0) params.organizationPicture = this.model.formData.imgList1[0].imgUrl
					if(this.model.formData.imgList.length>0) params.certificatePicture = this.model.formData.imgList[0].imgUrl
					// console.log(params); return
					let res = await API.serverApplication(params)
					if (res.code === 200) {
						uni.showToast({
							title: '服务方申请成功',
							icon: 'success'
						})
						this.timer = setTimeout(()=>{
							uni.reLaunch({
								url: '/pages/socialized-service/person-message/person-message'
							})
						},500)
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				}).catch(errors => {
					console.log("失败信息:" + JSON.stringify(errors))
				})
			},
			back() {
				uni.reLaunch({
					url: '/pages/socialized-service/person-message/person-message'
				})
			},
			setcollapseheight() {
				let topheightone = uni.upx2px(136)
				// let newheight = this.customBar + topheightone
				let winHeight = 0
				uni.getSystemInfo({
					success: function(res) {
						winHeight = res.windowHeight
					}
				});
				winHeight = parseInt(winHeight) - topheightone
				// #ifndef H5
				winHeight = winHeight
			
				// #endif
				return winHeight
			},
		}
	}
</script>

<style lang="scss" scoped>
	.lnglat {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 48rpx;
		border: 2rpx solid #0752fd;
		color: #0752fd;
		.icon {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			left: 65%;
		}
	}
	
	/deep/.u-form {
		padding: 0 32rpx;
	}

	/deep/.u-form-item {
		position: relative;
		background-color: #fff;
		margin-top: 20rpx;
		border-radius: 20rpx;
	}

	/deep/.u-form-item {
		&:nth-child(n+9) {
			background-color: #E2E7F8;
		}
	}

	.left-image {
		position: absolute;
		// top: 50%;
		// transform: translateY(-50%);
		left: 0;
		width: 54rpx;
		height: 54rpx;
		border-radius: 50%;
		margin-left: 22rpx;
		display: flex;
		justify-content: center;
		align-content: center;
		flex-wrap: wrap;
	}

	.left-img {
		height: 26rpx;
	}
	.u-form {
		/deep/ .u-icon--right {
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
		}
	}
	

	.uni-input-input {
		pointer-events: none;
	}

	/deep/ .u-form-item__body__left {
		width: 200rpx !important;
		margin-left: 50px;
	}

	.submit {
		margin-top: 60rpx;
		// position: absolute;
		// bottom: 150rpx;
		// left: 50%;
		// transform: translateX(-50%);

		.submit-btn {
			width: 340rpx;
			height: 60rpx;
			line-height: 60rpx;
			background: linear-gradient(270deg, #88ACFF 0%, #2165FF 100%);
			border-radius: 56rpx 56rpx 56rpx 56rpx;
			font-size: 28rpx;
			color: #FFFFFF;
			display: flex;
			justify-content: center;
			align-items: center;

			.icon-submit {
				margin-right: 10rpx;
			}
		}
	}

	/deep/ .u-upload__wrap {
		display: flex;
		align-items: center;
	}

	.blank {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
		align-items: center;
		justify-content: center;

		image {
			width: 104rpx;
			height: 114rpx;
		}

		.title {
			padding: 0 96rpx;
			padding-top: 38rpx;
			font-size: 32rpx
		}
	}
	
	/deep/ .u-upload__deletable__icon {
		top: 12rpx;
		right: 2rpx;
		transform: scale(1.7);
	}
	
	.fullAddress {
			display: flex;
			padding: 10rpx 0 !important;
	
			.textarea {
				width: 100%;
				padding: 0 !important;
				min-height: 114rpx !important;
				margin-right: 0;
			}
	
			/deep/.uni-textarea-textarea {
				padding: 2rpx !important;
				min-height: 114rpx !important;
			}
	
			/deep/ .uni-textarea-compute {
				flex: 1;
				min-height: 114rpx !important;
			}
		}
	
		/deep/.uni-textarea-wrapper {
			min-height: 114rpx !important;
		}
</style>